package com.gwall.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface MyInterface {
    Integer test(String name, Integer age);
}

class MyClass implements MyInterface {

    @Override
    public Integer test(String name, Integer age) {
        System.out.println("name = " + name);
        System.out.println("age = " + age);
        return 209;
    }
}

class MyHandler implements InvocationHandler {

    private Object target;

    public MyHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before method: " + method.getName());
        Object result = method.invoke(target, args);
        System.out.println("after method: " + method.getName());
        return result;
    }
}

public class MyJdkProxy {

    public static void main(String[] args) {

        MyClass model = new MyClass();

        MyHandler myHandler = new MyHandler(model);

        MyInterface o = (MyInterface)Proxy.newProxyInstance(
                model.getClass().getClassLoader(),
                model.getClass().getInterfaces(),
                myHandler
        );

        Integer result = o.test("Hello", 202);
        System.out.println("result = " + result);
    }

}
